<?php

namespace app\common\model;

use app\common\library\wechat\WxClient;
use app\common\library\wechat\WxCode;
use think\Log;
use think\Request;
use app\store\model\Setting as SettingModel;

/**
 * 用户模型类
 * Class User
 * @package app\common\model
 */
class User extends BaseModel
{
    protected $name = 'user';

    // 性别
    private $gender = ['未知', '男', '女'];

    /**
     * 关联收货地址表
     * @return \think\model\relation\HasMany
     */
    public function address()
    {
        return $this->hasMany('UserAddress');
    }

    /**
     * 关联收货地址表 (默认地址)
     * @return \think\model\relation\BelongsTo
     */
    public function addressDefault()
    {
        return $this->belongsTo('UserAddress', 'address_id');
    }

    /**
     * 显示性别
     * @param $value
     * @return mixed
     */
    public function getGenderAttr($value)
    {
        return $this->gender[$value];
    }

    public function makeShareImg(){
        if ($this->agent_level < 4) {
            try {
                //如果是代理生成小程序二维码
                $wxClient = new WxClient();
                $qrcode = $wxClient->getQrcode('pages/index/index', 'share_id-' . $this->user_id);
                $wxCode = new WxCode();
                $values = SettingModel::getItem("share");
                Log::record("share setting : " . json_encode($values));
                $bg = \app\common\model\UploadFile::get($values['bg'])->filePath;
                $dest = 'uploads/qrcodes/' . md5($this->user_id . time()) . '.png';
                $share_img = $wxCode->makeNewQrCodeAction($bg, $this->avatarUrl, $qrcode, $dest);
                return $share_img;
            } catch (\Exception $e) {
                Log::record("生成分享图片异常:" . $e->getMessage());
                Log::record("生成分享图片异常:" . $e->getFile());
                Log::record("生成分享图片异常:" . $e->getLine());
            }
        }
    }
    /**
     * 获取用户列表
     * @return \think\Paginator
     * @throws \think\exception\DbException
     */
    public function getList($filter=[])
    {
        $request = Request::instance();
        return $this->order(['create_time' => 'desc'])->where($filter)
            ->paginate(15, false, ['query' => $request->request()]);
    }

    /**
     * 获取用户信息
     * @param $where
     * @return null|static
     * @throws \think\exception\DbException
     */
    public static function detail($where)
    {
        return self::get($where, ['address', 'addressDefault']);
    }

}
